package com.nineclock.common.aliyun.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.nineclock.common.aliyun.oss.OssProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.InputStream;

/**
 * @author yangchao
 * @create 2022-01-13 14:17
 **/
//阿里云OSS开发工具包
@Component
public class OSSUtils {

    @Autowired
    private OSS ossClient;

    @Autowired
    private OssProperties ossProperties;

    //原始根地址
//    private String baseUrl = "https://heima-nine-clock.oss-cn-beijing.aliyuncs.com/";
    private String baseUrl;

    /**
     * 上传图片到OSS
     * @param imgFileName
     * @param inputStream
     * @return
     */
    public String uploadImgFile(String imgFileName, InputStream inputStream){

        //文件上传
        ossClient.putObject(ossProperties.getBucketName(), imgFileName,inputStream);

        //https://heima-nine-clock.oss-cn-beijing.aliyuncs.com/aaa.png
        //http://heima-nine-clock.oss-cn-beijing.aliyuncs.com/7f6d1f07-5288-4a2a-83ae-3ffb681aea0d.jpg?Expires=1642145270&OSSAccessKeyId=LTAI5tSYt9FXYMy4GrSCx1zR&Signature=JmGSZQDhs2WpuCJSpF9E1yrBkBk%3D
        //获取图片路径
        baseUrl = String.format(ossProperties.getHost(),ossProperties.getBucketName());
        String url = baseUrl + imgFileName;
//
//        //设置URL过期时间为24小时
//        Date expiration = new Date(System.currentTimeMillis() + 24 * 3600 * 1000);
//        //获取可以过期的url链接
//        String url = ossClient.generatePresignedUrl(ossProperties.getBucketName(), imgFileName, expiration).toString();

        return url;
    }

    /**
     * 删除OSS中的图片
     * @param imgFileName 文件的名称：如：aa.png
     */
    public void deleteImgFile(String imgFileName){
        ossClient.deleteObject(ossProperties.getBucketName(),imgFileName);
    }

}
